package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.FixedSizeQueue;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.system.domain.EqMsg;
import com.ruoyi.system.domain.EqOperation;
import com.ruoyi.system.domain.EqPool;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.domain.vo.MessageStatusVo;
import com.ruoyi.system.domain.vo.ValveVo;
import com.ruoyi.system.mapper.EqMsgMapper;
import com.ruoyi.system.mapper.EqPoolMapper;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.modbus.ModbusManager;
import com.ruoyi.system.service.IEqOperationService;
import com.ruoyi.system.service.IEqPoolService;
import com.ruoyi.system.service.InitService;
import com.ruoyi.system.socket.WebSocketServer;
import org.apache.commons.compress.utils.Lists;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;


@Service("initServiceImpl")
@EnableScheduling
public class InitServiceImpl implements InitService {

    @Autowired
    private SysConfigMapper configMapper;

    @Autowired
    private IEqPoolService eqPoolService;

    @Autowired
    private IEqOperationService iEqOperationService;

    @Autowired
    private EqPoolMapper eqPoolMapper;

    @Autowired
    private EqMsgMapper eqMsgMapper;

    @Autowired
    private ModbusManager modbusManager;

    @Autowired
    private ISysJobService jobService;

    public static FixedSizeQueue queue1 = new FixedSizeQueue(5);
    public static FixedSizeQueue queue2 = new FixedSizeQueue(5);
    public static FixedSizeQueue queue3 = new FixedSizeQueue(5);
    public static FixedSizeQueue queue4 = new FixedSizeQueue(5);
    public static FixedSizeQueue queue5 = new FixedSizeQueue(5);


    public void test(){

       /* System.err.println("1111111111111111111111111111111111111");
        SysConfig sysConfig3 = new SysConfig();
        sysConfig3.setConfigKey("b_auto_start");
        SysConfig sysConfigNew = configMapper.selectConfig(sysConfig3);
        if (1 == Integer.valueOf(sysConfigNew.getConfigValue())) {
            //自动逻辑
            startRun();
            //获取报警信息
            alarmMessage();
        }*/


    }
    public void test1(Integer status) throws SchedulerException {

        SysJob newJob = new SysJob();
        newJob.setStatus(status.toString());
        jobService.changeStatus(newJob);
    }

    @Override
    public AjaxResult setAuto(SysConfig sysConfig, String username) {
        SysConfig sysConfig1 = new SysConfig();
        sysConfig1.setConfigKey("update_password");
        //update_password
        SysConfig sysConfig2 = configMapper.selectConfig(sysConfig1);
        if (!sysConfig2.getConfigValue().equals(sysConfig.getConfigName())) {
            return AjaxResult.error("密码错误,不可更改");
        }
        EqOperation eqOperation = new EqOperation();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(username + " 于 " + DateUtils.getTime());
        if (1 == Integer.valueOf(sysConfig.getConfigValue())) {
            stringBuffer.append(" 将手动模式改为自动模式");
            updateAll();
            try {
                //test1(0);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            stringBuffer.append(" 将自动模式改为手动模式");
            try {
               // test1(1);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        SysConfig sysConfig3 = new SysConfig();
        sysConfig3.setConfigKey("b_auto_start");
        SysConfig sysConfigNew = configMapper.selectConfig(sysConfig3);

        sysConfig.setConfigId(sysConfigNew.getConfigId());//暂时写死
        sysConfig.setConfigName(null);
        int i = configMapper.updateConfig(sysConfig);
        if (i == 1) {
            return AjaxResult.success("更新成功");
        }
        eqOperation.setCreateName(username);
        eqOperation.setCreateTime(new Date());
        eqOperation.setOperation(stringBuffer.toString());
        iEqOperationService.insertEqOperation(eqOperation);
        return AjaxResult.error("更新失败");
    }


    private void updateAll() {
        // a1 a2 b1 b2 b3

        eqPoolMapper.updateAllPool();
        eqPoolMapper.updateAllPump();
        new Thread(new Runnable() {
            @Override
            public void run() {
                modbusManager.closeAll();
            }
        }).start();

    }

    @Override
    public AjaxResult getAutoAll() {
        List<EqPool> eqPools = eqPoolService.selectEqPoolList(null);
        return AjaxResult.success(eqPools);
    }

    @Override
    public AjaxResult updateAutoAll(ValveVo valveVo, String username) {
        EqOperation eqOperation = new EqOperation();
        StringBuffer stringBuffer = new StringBuffer();
        EqPool eqPool = eqPoolService.selectEqPoolById(valveVo.getEqId());
        if (null == eqPool) {
            return AjaxResult.error("水池ID错误,查询不到");
        }
        stringBuffer.append(username + " 于 " + DateUtils.getTime());
        if (1 == valveVo.getStatus()) {
            stringBuffer.append(" 开启 ");
        } else {
            stringBuffer.append(" 关闭 ");
        }
        stringBuffer.append(eqPool.getEquipmentName());
        if (1 == valveVo.getDirection()) {
            stringBuffer.append(" 进口阀门");
            eqPool.setInletValve(valveVo.getStatus());

        } else {
            stringBuffer.append(" 出口阀门");
            eqPool.setOutletValve(valveVo.getStatus());
        }
        controlValveDevice(eqPool.getB3(), eqPool.getInletValve(), eqPool.getOutletValve());

        int i = eqPoolService.updateEqPool(eqPool);
        if (1 == i) {
            eqOperation.setEquId(eqPool.getId());
            eqOperation.setEquName(eqPool.getEquipmentName());
            eqOperation.setCreateName(username);
            eqOperation.setCreateTime(new Date());
            eqOperation.setOperation(stringBuffer.toString());
            iEqOperationService.insertEqOperation(eqOperation);
            return AjaxResult.success("成功");
        }
        return AjaxResult.error("操作失败,请检查硬件设备.");
    }

    @Override
    public AjaxResult updateAutoPump(ValveVo valveVo, String username) {

        EqOperation eqOperation = new EqOperation();
        StringBuffer stringBuffer = new StringBuffer();
        EqPool eqPool = eqPoolService.selectEqPoolById(valveVo.getEqId());
        if (null == eqPool) {
            return AjaxResult.error("水池ID/泵ID错误,查询不到");
        }
        stringBuffer.append(username + " 于 " + DateUtils.getTime());

        if (1 == valveVo.getStatus()) {
            stringBuffer.append(" 开启 ");
        } else {
            stringBuffer.append(" 关闭 ");
        }
        eqPool.setPumpStatus(valveVo.getStatus());
        stringBuffer.append(eqPool.getEquipmentName());
        controlWaterPumpDevice(eqPool.getB3(), eqPool.getPumpStatus());
        int i = eqPoolService.updateEqPool(eqPool);
        eqOperation.setEquId(eqPool.getId());
        eqOperation.setEquName(eqPool.getEquipmentName());
        eqOperation.setCreateName(username);
        eqOperation.setCreateTime(new Date());
        eqOperation.setOperation(stringBuffer.toString());
        iEqOperationService.insertEqOperation(eqOperation);
        return AjaxResult.success("成功");

    }


    private void controlWaterPumpDevice(String tag, int status) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean b = modbusManager.controlWaterPumpDevice(tag, status);
            }
        }).start();

    }

    private void controlValveDevice(String tag, int inValveStatus, int outValveStatus) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean b = modbusManager.controlValveDevice(tag, inValveStatus, outValveStatus);
            }
        }).start();

    }

    @Override
    public AjaxResult getOperation() {
        List<EqOperation> eqOperations = iEqOperationService.selectEqOperationList(null);
        return AjaxResult.success(eqOperations);
    }

    @Override
    public AjaxResult getConfig() {
        SysConfig sysConfig1 = new SysConfig();
        sysConfig1.setConfigKey("b_auto_start");
        SysConfig sysConfig2 = configMapper.selectConfig(sysConfig1);
        return AjaxResult.success(sysConfig2);
    }

    @Override
    public AjaxResult setMessageStatus(MessageStatusVo messageStatusVo) {


        return null;
    }


    @Scheduled(fixedRate = 5000) //1000毫秒执行一次 , 检测自动的运行状态
    public void printTime() {

/*
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        String date = dateFormat.format(new Date());
        Iterator entries = WebSocketServer.webSocketMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            Object key = entry.getKey();
            WebSocketServer.sendInit(String.valueOf(key));
            WebSocketServer.sendInfo(JSON.toJSONString(new ReturunSocket(101,"心跳咚咚咚__1000毫秒一次___"+date)),String.valueOf(key));
        }
*/

        System.err.println("22222222222");
        SysConfig sysConfig3 = new SysConfig();
        sysConfig3.setConfigKey("b_auto_start");
        SysConfig sysConfigNew = configMapper.selectConfig(sysConfig3);
        if (1 == Integer.valueOf(sysConfigNew.getConfigValue())) {
            System.err.println("------------------------------开始时间======="+System.currentTimeMillis());
            //自动逻辑
            startRun();
            //获取报警信息
            alarmMessage();
            System.err.println("-------------------------------结束时间======="+System.currentTimeMillis());
        }
        sysConfig3 = null;
    }

    /* @Scheduled(fixedRate = 4000) //1000毫秒执行一次 , 检测自动的运行状态
      public void printTime111() {
          WebSocketServer.broadcast("11111");
      }*/
    private String alarmMessage() {
        /*
           报警信息
           1 主备不可以同时关闭 ( 泵1 2  34  沉淀池 1 2 )
           2 泵启动了 液位没有下降
         */
        EqPool eqPool1 = new EqPool();
        eqPool1.setB3("d1");
        List<EqPool> eqPools = eqPoolService.selectEqPoolList(eqPool1);
        EqPool eqPool = eqPools.get(0);
        Integer ballStatus = eqPool.getBallStatus();//2 关闭 1 开启

        if (1 == ballStatus) {
            if ("2".equals(eqPool.getB1())) {
                eqPool.setB1("1");
                //预警
                WebSocketServer.broadcast("应急池中存在异常水源,请立即核查!");
                EqMsg eqMsg = new EqMsg();
                eqMsg.setMsg("应急池中存在异常水源,请立即核查!");
                eqMsg.setCreateTime(new Date());
                eqMsg.setCreateName("系统自检");
                eqMsgMapper.insertEqMsg(eqMsg);
                eqMsg = null;
            }
        } else {
            eqPool.setB1("2");
        }
        eqPoolService.updateEqPool(eqPool);
        eqPool1 = null;
        eqPool = null;
        return null;
    }

    public static void main(String[] args) {

    }

    public static boolean isAllElementsEqual(Double[] arr, Double value) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].doubleValue() != value.doubleValue()) {
                return false;
            }
        }
        return true;
    }

    private String chendian123(String o) {
        StringBuffer stringBuffer = new StringBuffer();
        Boolean lock1 = false;
        Boolean lock2 = false;

        synchronized (queue1) {
            List<Double> list = Lists.newArrayList();
            Iterator<Double> iterator = queue1.iterator();
            while (iterator.hasNext()) {
                Double element = iterator.next();
                list.add(Double.valueOf(element));
            }
            Double[] doubles = list.toArray(new Double[5]);
            lock1 = isAllElementsEqual(doubles, doubles[0]); // true 说明一致
            doubles = null;
        }
        synchronized (queue2) {
            List<Double> list = Lists.newArrayList();
            Iterator<Double> iterator = queue2.iterator();
            while (iterator.hasNext()) {
                Double element = iterator.next();
                list.add(Double.valueOf(element));
            }
            Double[] doubles = list.toArray(new Double[5]);
            lock2 = isAllElementsEqual(doubles, doubles[0]); // true 说明一致
            doubles = null;
        }
        AtomicReference<Boolean> inCHi1 = new AtomicReference<>(false); // 衰变池1的进口阀门
        AtomicReference<Boolean> inCHi2 = new AtomicReference<>(false); // 衰变池3的进口阀门
        // 获取衰变池 1 2 3  的进口阀们状态
        EqPool eqPool1 = new EqPool();
        eqPool1.setB3("a1");
        List<EqPool> eqPools = eqPoolService.selectEqPoolList(eqPool1);
        inCHi1.set(eqPools.get(0).getOutletValve() == 1 ? true : false);
        eqPool1 = null;
        EqPool eqPool2 = new EqPool();
        eqPool2.setB3("a2");
        List<EqPool> eqPools1 = eqPoolService.selectEqPoolList(eqPool2);
        inCHi2.set(eqPools1.get(0).getOutletValve() == 1 ? true : false);
        eqPool2 = null;
        if (lock1) {
            //TODO 异常信息
            if (inCHi1.get()) {
                stringBuffer.append("沉淀池1的液位计存在异常请关注!");
            }
        }
        if (lock2) {
            //TODO 异常信息
            if (inCHi2.get()) {
                if (StringUtils.isNotEmpty(stringBuffer.toString())) {
                    stringBuffer.append("\n沉淀池2的液位计存在异常请关注!");
                } else {
                    stringBuffer.append("沉淀池2的液位计存在异常请关注!");
                }
            }
        }
        inCHi1 = null;
        inCHi2 = null;
        return stringBuffer.toString().length() > 0 ? stringBuffer.toString() : null;
    }

    private String chendian345(String o) {
        StringBuffer stringBuffer = new StringBuffer();
        Boolean lock1 = false;
        Boolean lock2 = false;
        Boolean lock3 = false;

        synchronized (queue3) {

            List<Double> list = Lists.newArrayList();
            Iterator<Double> iterator = queue3.iterator();
            while (iterator.hasNext()) {
                Double element = iterator.next();
                list.add(Double.valueOf(element));
            }
            Double[] doubles = list.toArray(new Double[5]);
            lock1 = isAllElementsEqual(doubles, doubles[0]); // true 说明一致
            doubles = null;
        }
        synchronized (queue4) {
            List<Double> list = Lists.newArrayList();
            Iterator<Double> iterator = queue4.iterator();
            while (iterator.hasNext()) {
                Double element = iterator.next();
                list.add(Double.valueOf(element));
            }
            Double[] doubles = list.toArray(new Double[5]);
            lock2 = isAllElementsEqual(doubles, doubles[0]); // true 说明一致
            doubles = null;
        }
        synchronized (queue5) {
            List<Double> list = Lists.newArrayList();
            Iterator<Double> iterator = queue5.iterator();
            while (iterator.hasNext()) {
                Double element = iterator.next();
                list.add(Double.valueOf(element));
            }
            Double[] doubles = list.toArray(new Double[5]);
            lock3 = isAllElementsEqual(doubles, doubles[0]); // true 说明一致
            doubles = null;
        }
        AtomicReference<Boolean> inCHi1 = new AtomicReference<>(false); // 衰变池1的进口阀门
        AtomicReference<Boolean> inCHi2 = new AtomicReference<>(false); // 衰变池3的进口阀门
        AtomicReference<Boolean> inCHi3 = new AtomicReference<>(false); // 衰变池3的进口阀门
        // 获取衰变池 1 2 3  的进口阀们状态
        EqPool eqPool1 = new EqPool();
        eqPool1.setB3("b1");
        List<EqPool> eqPools = eqPoolService.selectEqPoolList(eqPool1);
        inCHi1.set(eqPools.get(0).getOutletValve() == 1 ? true : false);
        eqPool1 = null;
        EqPool eqPool2 = new EqPool();
        eqPool2.setB3("b2");
        List<EqPool> eqPools1 = eqPoolService.selectEqPoolList(eqPool2);
        inCHi2.set(eqPools1.get(0).getOutletValve() == 1 ? true : false);
        eqPool2 = null;
        EqPool eqPool3 = new EqPool();
        eqPool3.setB3("b3");
        List<EqPool> eqPools2 = eqPoolService.selectEqPoolList(eqPool3);
        inCHi3.set(eqPools2.get(0).getOutletValve() == 1 ? true : false);
        eqPool3 = null;
        if (lock1) {
            //TODO 异常信息
            if (inCHi1.get()) {
                stringBuffer.append("衰变池1的液位计存在异常情关注!");
            }
        }
        if (lock2) {
            //TODO 异常信息
            if (inCHi2.get()) {
                if (StringUtils.isNotEmpty(stringBuffer.toString())) {
                    stringBuffer.append("\n衰变池2的液位计存在异常情关注!");
                } else {
                    stringBuffer.append("衰变池2的液位计存在异常情关注!");
                }
            }

        }
        if (lock3) {
            //TODO 异常信息
            if (inCHi3.get()) {
                if (StringUtils.isNotEmpty(stringBuffer.toString())) {
                    stringBuffer.append("\n衰变池3的液位计存在异常情关注!");
                } else {
                    stringBuffer.append("衰变池3的液位计存在异常情关注!");
                }
            }
        }
        inCHi1 = null;
        inCHi2 = null;
        inCHi3 = null;

        return stringBuffer.toString().length() > 0 ? stringBuffer.toString() : null;
    }


    private String threadMsg(EqPool o) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(6000);//线程睡眠一秒，根据业务不同可以除去
                    String s = chendian123(o.getB3());
                    if (StringUtils.isNotEmpty(s)) {
                        WebSocketServer.broadcast(s);
                        EqMsg eqMsg = new EqMsg();
                        eqMsg.setMsg(s);
                        eqMsg.setCreateTime(new Date());
                        eqMsg.setCreateName("系统自检");
                        eqMsgMapper.insertEqMsg(eqMsg);
                        eqMsg = null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(r).start();
        return null;
    }

    private String threadMsg345(EqPool o) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(6000);//线程睡眠一秒，根据业务不同可以除去
                    String s = chendian345(o.getB3());
                    if (StringUtils.isNotEmpty(s)) {
                        WebSocketServer.broadcast(s);
                        EqMsg eqMsg = new EqMsg();
                        eqMsg.setMsg(s);
                        eqMsg.setCreateTime(new Date());
                        eqMsg.setCreateName("系统自检");
                        eqMsgMapper.insertEqMsg(eqMsg);
                        eqMsg = null;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(r).start();
        return null;
    }

    private String startRun() {
        //TODO 初始化判断 主备是否都关闭 都关闭了 则不可运行并报异常
        final AtomicReference<EqPool> a1 = new AtomicReference<>();
        List<EqPool> eqPool = eqPoolService.selectEqPoolList(null);
        eqPool.forEach(o -> {
            // 1 启动 2 关闭
            //处理第一个沉淀池
            if (o.getB3().equals("a1")) {
                synchronized (queue1) {
                    queue1.offer(o.getCurrentAltitude().doubleValue());
                }
                chendian1(o);
                o.setB2(null);
                eqPoolService.updateEqPool(o);
                a1.set(o);
                //a1.set(o);
            }
            //处理第二个沉淀池
            if (o.getB3().equals("a2")) {
                synchronized (queue2) {
                    queue2.offer(o.getCurrentAltitude().doubleValue());
                }
                chendian2(o,a1);
                o.setB2(null);
                eqPoolService.updateEqPool(o);
            } //处理第一个衰变池
            if (o.getB3().equals("b1")) {
                synchronized (queue3) {
                    queue3.offer(o.getCurrentAltitude().doubleValue());
                }
                shuaibianchi1(o);
                o.setB2(null);
                eqPoolService.updateEqPool(o);
            } //处理第二个衰变池
            if (o.getB3().equals("b2")) {
                synchronized (queue4) {
                    queue4.offer(o.getCurrentAltitude().doubleValue());
                }
                shuaibianchi2(o);
                o.setB2(null);
                eqPoolService.updateEqPool(o);
            } //处理第三个衰变池
            if (o.getB3().equals("b3")) {
                synchronized (queue5) {
                    queue5.offer(o.getCurrentAltitude().doubleValue());
                }
                shuaibianchi3(o);
                o.setB2(null);
                eqPoolService.updateEqPool(o);
            } //处理第一个应急池
            if (o.getB3().equals("c1")) {

            } //处理第一个悬浮球
            if (o.getB3().equals("d1")) {

            } //处理第一个水泵
            if (o.getB3().equals("e1")) {
                startBeng1(o);
                o.setB2(null);
                eqPoolService.updateEqPool(o);
            } //处理第二个水泵
            if (o.getB3().equals("e2")) {
                startBeng2(o);
                o.setB2(null);
                eqPoolService.updateEqPool(o);
            } //处理第三个水泵
            if (o.getB3().equals("e3")) {
                startBeng3(o);
                o.setB2(null);
                eqPoolService.updateEqPool(o);
            } //处理第四个水泵
            if (o.getB3().equals("e4")) {
                startBeng4(o);
                o.setB2(null);
                eqPoolService.updateEqPool(o);
            }
        });
        eqPool = null;
        System.gc();
        return null;
    }


    private String chendian1(EqPool o) {
        if (o.getB2() != 0) {
            //TODO 关闭1号沉淀池的进口 和出口
            o.setInletValve(2);
            o.setOutletValve(2);
            controlValveDevice(o.getB3(), 2, 2);
            return "";
        }
        BigDecimal measurementUp = o.getMeasurementUp(); //液位上限
        BigDecimal measurementLow = o.getMeasurementLow();//液位下线
        BigDecimal currentAltitude = o.getCurrentAltitude();//实时液位
        AtomicReference<Boolean> inCHi2 = new AtomicReference<>(false); // 沉淀池1的进口阀门
        EqPool eqPool1 = new EqPool();
        eqPool1.setB3("a2");
        List<EqPool> eqPools = eqPoolService.selectEqPoolList(eqPool1);
        inCHi2.set(eqPools.get(0).getInletValve() == 1 ? true : false);
        eqPool1 =null;
        // 开放出口
        if (!inCHi2.get()) {
            //TODO 开放1号进水口
            controlValveDevice(o.getB3(), 1, 0);
            o.setInletValve(1);
        } else {
            //TODO 关闭1号沉淀池的进口 和出口
            controlValveDevice(o.getB3(), 0, 2);
            o.setOutletValve(2);
        }
        //加满了
        if (measurementUp.doubleValue() < currentAltitude.doubleValue()) {
            //TODO 关闭1号沉淀池的进口 和出口
            controlValveDevice(o.getB3(), 0, 1);
            o.setOutletValve(1);
        }
        //出水阀打开
        if (measurementLow.doubleValue() > currentAltitude.doubleValue()) {
            //TODO 关闭1号沉淀池的进口 和出口
            controlValveDevice(o.getB3(), 0, 2);
            o.setOutletValve(2);
        }
        measurementUp = null;
        measurementLow = null;
        currentAltitude = null;
        return "";
    }

    private String chendian2(EqPool o,AtomicReference<EqPool> a1 ) {
        if (o.getB2() != 0 ) {
            //TODO 关闭2号沉淀池的进口 和出口
            o.setInletValve(2);
            o.setOutletValve(2);
            controlValveDevice(o.getB3(), 2, 2);
            return "";
        }
        BigDecimal measurementUp = o.getMeasurementUp(); //液位上限
        BigDecimal measurementLow = o.getMeasurementLow();//液位下线
        BigDecimal currentAltitude = o.getCurrentAltitude();//实时液位
        AtomicReference<Boolean> inCHi1 = new AtomicReference<>(false); // 沉淀池1的进口阀门
        EqPool eqPool1 = new EqPool();
        eqPool1.setB3("a1");
        List<EqPool> eqPools = eqPoolService.selectEqPoolList(eqPool1);
        inCHi1.set(eqPools.get(0).getInletValve() == 1 ? true : false);
        eqPool1 = null;
        // 开放出口
        if (!inCHi1.get() && eqPools.get(0).getB2() != 0) {
            //TODO 开放2号进水口
            controlValveDevice(o.getB3(), 1, 0);
            o.setInletValve(1);
        } else {
            controlValveDevice(o.getB3(), 0, 2);
            o.setOutletValve(2);
        }
        //加满了
        if (measurementUp.doubleValue() < currentAltitude.doubleValue()) {
            controlValveDevice(o.getB3(), 0, 1);
            o.setOutletValve(1);
        }
        //出水阀打开
        if (measurementLow.doubleValue() > currentAltitude.doubleValue()) {
            controlValveDevice(o.getB3(), 0, 2);
            o.setOutletValve(2);
        }

        if((null == a1.get().getB2() || a1.get().getB2() == 0)){
            o.setInletValve(2);
            controlValveDevice(o.getB3(), 2, 2);
        }

        measurementUp = null;
        measurementLow = null;
        currentAltitude = null;
        return "";
    }

    private String startBeng1(EqPool o) {
        if (o.getB2() != 0) {
            //TODO 关闭1号泵
            o.setPumpStatus(2);
            controlWaterPumpDevice(o.getB3(), 2);
            return "";
        }
        AtomicReference<Boolean> inCHi1 = new AtomicReference<>(false); // 衰变池1的进口阀门
        AtomicReference<Boolean> inCHi2 = new AtomicReference<>(false); // 衰变池3的进口阀门
        AtomicReference<Boolean> inCHi3 = new AtomicReference<>(false); // 衰变池3的进口阀门
        AtomicReference<Boolean> inCHi4 = new AtomicReference<>(false); // 衰变池3的进口阀门
        // 获取衰变池 1 2 3  的进口阀们状态
        EqPool eqPool1 = new EqPool();
        eqPool1.setB3("a1");
        List<EqPool> eqPools = eqPoolService.selectEqPoolList(eqPool1);
        inCHi1.set(eqPools.get(0).getOutletValve() == 1 ? true : false);
        eqPool1 = null;
        EqPool eqPool2 = new EqPool();
        eqPool2.setB3("a2");
        List<EqPool> eqPools1 = eqPoolService.selectEqPoolList(eqPool2);
        inCHi2.set(eqPools1.get(0).getOutletValve() == 1 ? true : false);
        eqPool2 = null;
        EqPool eqPool3 = new EqPool();
        eqPool3.setB3("d1");
        List<EqPool> eqPools3 = eqPoolService.selectEqPoolList(eqPool3);
        inCHi3.set(eqPools3.get(0).getBallStatus() == 1 ? true : false);
        eqPool3 = null;
        EqPool eqPool4 = new EqPool();
        eqPool4.setB3("e2");
        List<EqPool> eqPools4 = eqPoolService.selectEqPoolList(eqPool4);
        inCHi4.set(eqPools4.get(0).getPumpStatus() == 1 ? true : false);
        eqPool4 = null;
        if ((inCHi1.get() || inCHi2.get() || inCHi3.get()) && !inCHi4.get()) {
            if (1 != o.getPumpStatus()) {
                threadMsg(o);
                o.setPumpStatus(1);
                controlWaterPumpDevice(o.getB3(), 1);
            }
        } else {
            o.setPumpStatus(2);
            controlWaterPumpDevice(o.getB3(), 2);
        }

        if (o.getB2() != 0) {
        }else{
            if((inCHi1.get() || inCHi2.get() || inCHi3.get()) ){
                o.setPumpStatus(1);
                controlWaterPumpDevice(o.getB3(), 1);
            }
        }

        inCHi1 = null;
        inCHi2 = null;
        inCHi3 = null;
        inCHi4 = null;

        return "";
    }

    private String startBeng2(EqPool o) {
        if (o.getB2() != 0) {
            //TODO 关闭3号泵
            o.setPumpStatus(2);
            controlWaterPumpDevice(o.getB3(), 2);
            return "";
        }
        AtomicReference<Boolean> inCHi1 = new AtomicReference<>(false); // 衰变池1的进口阀门
        AtomicReference<Boolean> inCHi2 = new AtomicReference<>(false); // 衰变池3的进口阀门
        AtomicReference<Boolean> inCHi3 = new AtomicReference<>(false); // 衰变池3的进口阀门
        AtomicReference<Boolean> inCHi4 = new AtomicReference<>(false); // 衰变池3的进口阀门
        // 获取衰变池 1 2 3  的进口阀们状态
        EqPool eqPool1 = new EqPool();
        eqPool1.setB3("a1");
        List<EqPool> eqPools = eqPoolService.selectEqPoolList(eqPool1);
        inCHi1.set(eqPools.get(0).getOutletValve() == 1 ? true : false);
        eqPool1 = null;
        EqPool eqPool2 = new EqPool();
        eqPool2.setB3("a2");
        List<EqPool> eqPools1 = eqPoolService.selectEqPoolList(eqPool2);
        inCHi2.set(eqPools1.get(0).getOutletValve() == 1 ? true : false);
        eqPool2 =null;
        EqPool eqPool3 = new EqPool();
        eqPool3.setB3("d1");
        List<EqPool> eqPools3 = eqPoolService.selectEqPoolList(eqPool3);
        inCHi3.set(eqPools3.get(0).getBallStatus() == 1 ? true : false);
        eqPool3 = null;
        EqPool eqPool4 = new EqPool();
        eqPool4.setB3("e1");
        List<EqPool> eqPools4 = eqPoolService.selectEqPoolList(eqPool4);
        inCHi4.set(eqPools4.get(0).getPumpStatus() == 1 ? true : false);
        eqPool4 = null;
        if ((inCHi1.get() || inCHi2.get() || inCHi3.get()) && !inCHi4.get()) {
            if (1 != o.getPumpStatus()) {
                threadMsg(o);
                o.setPumpStatus(1);
                controlWaterPumpDevice(o.getB3(), 1);
            }
        } else {
            o.setPumpStatus(2);
            controlWaterPumpDevice(o.getB3(), 2);
        }
        inCHi1 = null;
        inCHi2 = null;
        inCHi3 = null;
        inCHi4 = null;
        return "";
    }


    private String startBeng3(EqPool o) {
        if (o.getB2() != 0) {
            //TODO 关闭3号泵
            o.setPumpStatus(2);
            controlWaterPumpDevice(o.getB3(), 2);
            return "";
        }
        AtomicReference<Boolean> inCHi1 = new AtomicReference<>(false); // 衰变池1的进口阀门
        AtomicReference<Boolean> inCHi2 = new AtomicReference<>(false); // 衰变池3的进口阀门
        AtomicReference<Boolean> inCHi3 = new AtomicReference<>(false); // 衰变池3的进口阀门
        AtomicReference<Boolean> inCHi4 = new AtomicReference<>(false); // 衰变池3的进口阀门
        // 获取衰变池 1 2 3  的进口阀们状态
        EqPool eqPool1 = new EqPool();
        eqPool1.setB3("b1");
        List<EqPool> eqPools = eqPoolService.selectEqPoolList(eqPool1);
        inCHi1.set(eqPools.get(0).getOutletValve() == 1 ? true : false);
        eqPool1 = null;
        EqPool eqPool2 = new EqPool();
        eqPool2.setB3("b2");
        List<EqPool> eqPools1 = eqPoolService.selectEqPoolList(eqPool2);
        inCHi2.set(eqPools1.get(0).getOutletValve() == 1 ? true : false);
        eqPool2 = null;
        EqPool eqPool3 = new EqPool();
        eqPool3.setB3("b3");
        List<EqPool> eqPools3 = eqPoolService.selectEqPoolList(eqPool3);
        inCHi3.set(eqPools3.get(0).getOutletValve() == 1 ? true : false);
        eqPool3 = null;
        EqPool eqPool4 = new EqPool();
        eqPool4.setB3("e4");
        List<EqPool> eqPools4 = eqPoolService.selectEqPoolList(eqPool4);
        inCHi4.set(eqPools4.get(0).getPumpStatus() == 1 ? true : false);
        eqPool4 = null;

        if ((inCHi1.get() || inCHi2.get() || inCHi3.get()) && (!inCHi4.get())) {
            if (1 != o.getPumpStatus()) {
                o.setPumpStatus(1);
                threadMsg345(o);
                controlWaterPumpDevice(o.getB3(), 1);
            }
        } else {
            o.setPumpStatus(2);
            controlWaterPumpDevice(o.getB3(), 2);
        }

        if (o.getB2() != 0) {
        }else{
            if((inCHi1.get() || inCHi2.get() || inCHi3.get())){
                o.setPumpStatus(1);
                controlWaterPumpDevice(o.getB3(), 1);
            }
        }

        inCHi1 = null;
        inCHi2 = null;
        inCHi3 = null;
        inCHi4 = null;
        return "";
    }

    private String startBeng4(EqPool o) {
        if (o.getB2() != 0) {
            //TODO 关闭4号泵
            o.setPumpStatus(2);
            controlWaterPumpDevice(o.getB3(), 2);
            return "";
        }
        AtomicReference<Boolean> inCHi1 = new AtomicReference<>(false); // 衰变池1的进口阀门
        AtomicReference<Boolean> inCHi2 = new AtomicReference<>(false); // 衰变池3的进口阀门
        AtomicReference<Boolean> inCHi3 = new AtomicReference<>(false); // 衰变池3的进口阀门
        AtomicReference<Boolean> inCHi4 = new AtomicReference<>(false); // 衰变池3的进口阀门
        // 获取衰变池 1 2 3  的进口阀们状态
        EqPool eqPool1 = new EqPool();
        eqPool1.setB3("b1");
        List<EqPool> eqPools = eqPoolService.selectEqPoolList(eqPool1);
        inCHi1.set(eqPools.get(0).getOutletValve() == 1 ? true : false);
        eqPool1 = null;
        EqPool eqPool2 = new EqPool();
        eqPool2.setB3("b2");
        List<EqPool> eqPools1 = eqPoolService.selectEqPoolList(eqPool2);
        inCHi2.set(eqPools1.get(0).getOutletValve() == 1 ? true : false);
        eqPool2 = null;
        EqPool eqPool3 = new EqPool();
        eqPool3.setB3("b3");
        List<EqPool> eqPools3 = eqPoolService.selectEqPoolList(eqPool3);
        inCHi3.set(eqPools3.get(0).getOutletValve() == 1 ? true : false);
        eqPool3 = null;
        EqPool eqPool4 = new EqPool();
        eqPool4.setB3("e3");
        List<EqPool> eqPools4 = eqPoolService.selectEqPoolList(eqPool4);
        inCHi4.set(eqPools4.get(0).getPumpStatus() == 1 ? true : false);
        eqPool4 = null;
        if ((inCHi1.get() || inCHi2.get() || inCHi3.get()) && !inCHi4.get()) {
            if (1 != o.getPumpStatus()) {
                o.setPumpStatus(1);
                threadMsg345(o);
                controlWaterPumpDevice(o.getB3(), 1);
            }
        } else {
            o.setPumpStatus(2);
            controlWaterPumpDevice(o.getB3(), 2);
        }
        inCHi1 = null;
        inCHi2 = null;
        inCHi3 = null;
        inCHi4 = null;
        return "";
    }

    /*
        衰变池1
     */
    private String shuaibianchi1(EqPool o) {
        if (o.getB2() != 0) {
            //TODO 关闭进出口阀门
            o.setInletValve(2);
            o.setOutletValve(2);
            controlValveDevice(o.getB3(), 2, 2);
            return "";
        }
        BigDecimal measurementUp = o.getMeasurementUp(); //液位上限
        BigDecimal measurementLow = o.getMeasurementLow();//液位下线
        BigDecimal currentAltitude = o.getCurrentAltitude();//实时液位
        Date effectiveTime = o.getEffectiveTime();// 开始沉淀时间
        AtomicReference<Boolean> inCHi1 = new AtomicReference<>(false); // 衰变池1的进口阀门
        AtomicReference<Boolean> inCHi2 = new AtomicReference<>(false); // 衰变池3的进口阀门
        // 获取衰变池 1 2 的进口阀们状态
        EqPool eqPool1 = new EqPool();
        eqPool1.setB3("b2");
        List<EqPool> eqPools = eqPoolService.selectEqPoolList(eqPool1);
        inCHi1.set(eqPools.get(0).getInletValve() == 1 ? true : false);
        eqPool1 = null;
        EqPool eqPool2 = new EqPool();
        eqPool2.setB3("b3");
        List<EqPool> eqPools1 = eqPoolService.selectEqPoolList(eqPool2);
        inCHi2.set(eqPools1.get(0).getInletValve() == 1 ? true : false);
        eqPool2 = null;
        /*
          1 水没满就开启进口阀门 , 不管日期到不到都开进口阀门 关闭出口阀门
          2 水满了 并且 还没到沉淀日期 则一直               关闭1号 进出口阀门  尝试开启2号的进口 3号
          3 水满了 并且 沉淀日期到了                       开启出口阀门 二号的进口   等到 实际液位 低于 下限的时候 关闭出口阀门 打开进口阀门
          4 如果2号池子 或者 三号池子 开启 同一时间只能开启一个进口阀门
         */
        if (null == effectiveTime) {
            //TODO 关闭出口阀
            controlValveDevice(o.getB3(), 0, 2);
            o.setOutletValve(2);
        }
        //TODO 处理开门
        //  1 3 门都关着 并且 水位达不到上限 并且 没有开始计时
        if ((!inCHi2.get() && !inCHi1.get()) && measurementUp.doubleValue() > currentAltitude.doubleValue() && null == effectiveTime) {
            //TODO 打开衰变池2的进口阀门
            controlValveDevice(o.getB3(), 1, 0);
            o.setInletValve(1);
        }
        //刚开始沉淀
        if (measurementUp.doubleValue() < currentAltitude.doubleValue()) {
            if (o.getEffectiveTime() == null) {
                //TODO 关闭进出口阀门
                controlValveDevice(o.getB3(), 2, 2);
                o.setInletValve(2);
                o.setOutletValve(2);
                o.setEffectiveTime(new Date());
            }
        }
        //沉淀中
        if (null != o.getEffectiveTime()) {
            //判断开始沉淀时间
            Boolean aBoolean = DateUtils.compareDate(o.getTimeOut(), o.getEffectiveTime());
            if (aBoolean) {  // 达到排放时间 开启出口阀门
                // TODO 开启衰变池1号的 出口阀门
                controlValveDevice(o.getB3(), 0, 1);
                o.setOutletValve(1);
            } else {
                // TODO 开启衰变池1号的 出口阀门
                controlValveDevice(o.getB3(), 2, 2);
                o.setInletValve(2);
                o.setOutletValve(2);
            }
        }
        //沉淀结束
        if (measurementLow.doubleValue() > currentAltitude.doubleValue() && null != effectiveTime) {
            //TODO 停止出口阀门
            o.setOutletValve(2);
            controlValveDevice(o.getB3(), 0, 2);
            //TODO  注意需要关闭泵 3 4 排水 没写
            o.setEffectiveTime(null); // 清空时间
            eqPoolMapper.updateEqPoolNew(o);
        }
        measurementUp = null;
        measurementLow = null;
        currentAltitude = null;
        return "";
    }

    private String shuaibianchi2(EqPool o) {
        if (o.getB2() != 0) {
            //TODO 关闭进出口阀门
            o.setInletValve(2);
            o.setOutletValve(2);
            controlValveDevice(o.getB3(), 2, 2);
            return "";
        }
        BigDecimal measurementUp = o.getMeasurementUp(); //液位上限
        BigDecimal measurementLow = o.getMeasurementLow();//液位下线
        BigDecimal currentAltitude = o.getCurrentAltitude();//实时液位
        Date effectiveTime = o.getEffectiveTime();// 开始沉淀时间
        AtomicReference<Boolean> inCHi1 = new AtomicReference<>(false); // 衰变池1的进口阀门
        AtomicReference<Boolean> inCHi3 = new AtomicReference<>(false); // 衰变池3的进口阀门
        // 获取衰变池 1 3 的进口阀们状态
        EqPool eqPool1 = new EqPool();
        eqPool1.setB3("b1");
        List<EqPool> eqPools = eqPoolService.selectEqPoolList(eqPool1);
        inCHi1.set(eqPools.get(0).getInletValve() == 1 ? true : false);
        eqPool1 = null;
        EqPool eqPool3 = new EqPool();
        eqPool3.setB3("b3");
        List<EqPool> eqPools1 = eqPoolService.selectEqPoolList(eqPool3);
        inCHi3.set(eqPools1.get(0).getInletValve() == 1 ? true : false);
        eqPool3 =null;
                /*
                    1 水没满就开启进口阀门 , 不管日期到不到都开进口阀门 关闭出口阀门
                    2 水满了 并且 还没到沉淀日期 则一直               关闭1号 进出口阀门  尝试开启2号的进口 3号
                    3 水满了 并且 沉淀日期到了                       开启出口阀门 二号的进口   等到 实际液位 低于 下限的时候 关闭出口阀门 打开进口阀门
                    4 如果2号池子 或者 三号池子 开启 同一时间只能开启一个进口阀门
                */
        if (null == effectiveTime) {
            //TODO 关闭出口阀
            controlValveDevice(o.getB3(), 0, 2);
            o.setOutletValve(2);
        }
        //TODO 处理开门
        //  1 3 门都关着 并且 水位达不到上限 并且 没有开始计时
        if ((!inCHi3.get() && !inCHi1.get()) && measurementUp.doubleValue() > currentAltitude.doubleValue() && null == effectiveTime) {
            //TODO 打开衰变池2的进口阀门
            controlValveDevice(o.getB3(), 1, 0);
            o.setInletValve(1);
        }
        //刚开始沉淀
        if (measurementUp.doubleValue() < currentAltitude.doubleValue()) {
            if (o.getEffectiveTime() == null) {
                //TODO 关闭进出口阀门
                o.setInletValve(2);
                o.setOutletValve(2);
                controlValveDevice(o.getB3(), 2, 2);
                o.setEffectiveTime(new Date());
            }
        }
        //沉淀中
        if (null != o.getEffectiveTime()) {
            //判断开始沉淀时间
            Boolean aBoolean = DateUtils.compareDate(o.getTimeOut(), o.getEffectiveTime());
            if (aBoolean) {  // 达到排放时间 开启出口阀门
                // TODO 开启衰变池1号的 出口阀门
                controlValveDevice(o.getB3(), 0, 1);
                o.setOutletValve(1);
            } else {
                // TODO 开启衰变池1号的 出口阀门
                o.setInletValve(2);
                o.setOutletValve(2);
                controlValveDevice(o.getB3(), 2, 2);
            }
        }
        //沉淀结束
        if (measurementLow.doubleValue() > currentAltitude.doubleValue() && null != effectiveTime) {
            //TODO 停止出口阀门
            o.setOutletValve(2);
            controlValveDevice(o.getB3(), 0, 2);
            //TODO  注意需要关闭泵 3 4 排水 没写
            o.setEffectiveTime(null); // 清空时间
            eqPoolMapper.updateEqPoolNew(o);
        }
        //如果 其他阀门开启了 则关闭 当前关闭阀门
        if (inCHi1.get()) {
            controlValveDevice(o.getB3(), 2, 0);
            o.setInletValve(2);
        }
        measurementUp = null;
        measurementLow = null;
        currentAltitude = null;
        return "";
    }

    private String shuaibianchi3(EqPool o) {
        if (o.getB2() != 0) {
            //TODO 关闭三号衰变池进出口阀门
            o.setInletValve(2);
            o.setOutletValve(2);
            controlValveDevice(o.getB3(), 2, 2);
            return "";
        }
        BigDecimal measurementUp = o.getMeasurementUp(); //液位上限
        BigDecimal measurementLow = o.getMeasurementLow();//液位下线
        BigDecimal currentAltitude = o.getCurrentAltitude();//实时液位
        Date effectiveTime = o.getEffectiveTime();// 开始沉淀时间
        AtomicReference<Boolean> inCHi1 = new AtomicReference<>(false); // 衰变池1的进口阀门
        AtomicReference<Boolean> inCHi2 = new AtomicReference<>(false); // 衰变池2的进口阀门
        // 获取衰变池 1 2 的进口阀们状态
        EqPool eqPool1 = new EqPool();
        eqPool1.setB3("b1");
        List<EqPool> eqPools = eqPoolService.selectEqPoolList(eqPool1);
        inCHi1.set(eqPools.get(0).getInletValve() == 1 ? true : false);
        eqPool1 = null;
        EqPool eqPool2 = new EqPool();
        eqPool2.setB3("b2");
        List<EqPool> eqPools1 = eqPoolService.selectEqPoolList(eqPool2);
        inCHi2.set(eqPools1.get(0).getInletValve() == 1 ? true : false);
        eqPool2 =null;
                /*
                    1 水没满就开启进口阀门 , 不管日期到不到都开进口阀门 关闭出口阀门
                    2 水满了 并且 还没到沉淀日期 则一直               关闭1号 进出口阀门  尝试开启2号的进口 3号
                    3 水满了 并且 沉淀日期到了                       开启出口阀门 二号的进口   等到 实际液位 低于 下限的时候 关闭出口阀门 打开进口阀门
                    4 如果2号池子 或者 三号池子 开启 同一时间只能开启一个进口阀门
                */
        if (null == effectiveTime) {
            //TODO 关闭出口阀
            controlValveDevice(o.getB3(), 0, 2);
            o.setOutletValve(2);
        }

        //TODO 处理开门
        //  1 3 门都关着 并且 水位达不到上限 并且 没有开始计时
        if ((!inCHi2.get() && !inCHi1.get()) && measurementUp.doubleValue() > currentAltitude.doubleValue() && null == effectiveTime) {
            //TODO 打开衰变池2的进口阀门
            controlValveDevice(o.getB3(), 1, 0);
            o.setInletValve(1);
        }
        //刚开始沉淀
        if (measurementUp.doubleValue() < currentAltitude.doubleValue()) {
            if (o.getEffectiveTime() == null) {
                //TODO 关闭进出口阀门
                o.setInletValve(2);
                o.setOutletValve(2);
                controlValveDevice(o.getB3(), 2, 2);
                o.setEffectiveTime(new Date());
            }
        }
        //沉淀中
        if (null != o.getEffectiveTime()) {
            //判断开始沉淀时间
            Boolean aBoolean = DateUtils.compareDate(o.getTimeOut(), o.getEffectiveTime());
            if (aBoolean) {  // 达到排放时间 开启出口阀门
                // TODO 开启衰变池1号的 出口阀门
                o.setOutletValve(1);
                controlValveDevice(o.getB3(), 0, 1);
            } else {
                // TODO 开启衰变池1号的 出口阀门
                o.setInletValve(2);
                o.setOutletValve(2);
                controlValveDevice(o.getB3(), 2, 2);
            }
        }
        //沉淀结束
        if (measurementLow.doubleValue() > currentAltitude.doubleValue() && null != effectiveTime) {
            //TODO 停止出口阀门
            o.setOutletValve(2);
            controlValveDevice(o.getB3(), 0, 2);
            //TODO  注意需要关闭泵 3 4 排水 没写
            o.setEffectiveTime(null); // 清空时间
            eqPoolMapper.updateEqPoolNew(o);
        }
        //如果 其他阀门开启了 则关闭 当前关闭阀门
        if (inCHi2.get()) {
            controlValveDevice(o.getB3(), 2, 0);
            o.setInletValve(2);
        }
        measurementUp = null;
        measurementLow = null;
        currentAltitude = null;
        return "";
    }


}
